#include "atom.h"
#include "atomtimer.h"
#include "syslog.h"
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#undef OK
#include "FreeRTOS.h"
#include "timers.h"

uint8_t atomTimerDelay(uint32_t ticks)
{
    vTaskDelay(ticks);
	return ATOM_OK;
}

uint8_t atomTimerDelayMs(uint32_t ms)
{
    vTaskDelay(pdMS_TO_TICKS(ms));
	return ATOM_OK;
}

static void timer_handler( TimerHandle_t xTimer )
{
    ATOM_TIMER *timer = (ATOM_TIMER *) pvTimerGetTimerID(xTimer);
    
    if (timer->cb_func != NULL) {
        timer->cb_func(timer->cb_data);
    }
}

uint8_t atomTimerRegister(ATOM_TIMER* timer_ptr)
{
    if (timer_ptr == NULL || timer_ptr->cb_func == NULL || timer_ptr->cb_ticks == 0)
    {
        return ATOM_ERROR;
    }

    timer_ptr->handle = (POINTER)xTimerCreate(
        NULL,                           /* 定时器名称 */
        pdMS_TO_TICKS(timer_ptr->cb_ticks),/* 定时周期（以tick为单位） */
        (timer_ptr->cb_loop ? pdTRUE : pdFALSE),                           /* pdFALSE 表示一次性定时器, pdTRUE 表示周期性定时器 */
        (void*)timer_ptr,                  /* 定时器唯一标识 */
        timer_handler/* 定时器回调函数 */
    );

    if (timer_ptr->handle == NULL)
    {
        return ATOM_ERROR;
    }

    if (xTimerStart(timer_ptr->handle, 0) != pdPASS)
    {
        return ATOM_ERROR;
    }

    return ATOM_OK;
}

uint8_t atomTimerCancel(ATOM_TIMER* timer_ptr)
{
    if (timer_ptr == NULL || timer_ptr->handle == NULL)
    {
        return ATOM_ERROR;
    }

    // 停止计时器
    if (xTimerStop(timer_ptr->handle, 0) != pdPASS)
    {
        return ATOM_ERROR;
    }

    // 删除计时器
    if (xTimerDelete(timer_ptr->handle, 0) != pdPASS)
    {
        return ATOM_ERROR;
    }

    timer_ptr->handle = NULL;
    timer_ptr->cb_func = NULL;
    timer_ptr->cb_data = NULL;
    timer_ptr->cb_ticks = 0;

    return ATOM_OK;
}

uint32_t atomTimeGet(void)
{
    TickType_t currentTicks = xTaskGetTickCount();
    return currentTicks;
}

void atomTimeSet(uint32_t new_time)
{
    SYSLOG(LOG_NOTICE, "atomTimeSet not implemented under vos!");
}

uint32_t atomUserTimerWakeupTimeGet(void)
{
    SYSLOG(LOG_NOTICE, "atomUserTimerWakeupTimeGet not implemented under vos!");
    return (ATOM_ERROR);
}

void atomUserTimerUpdate(uint32_t sleep_time)
{
    SYSLOG(LOG_NOTICE, "atomUserTimerUpdate not implemented under vos!");
}